package com.kpijavatraining.module.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class FileWriter {

	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private Document document;
		
	public FileWriter() throws ParserConfigurationException, SAXException, IOException{
		factory  = DocumentBuilderFactory.newInstance();
		builder  = factory.newDocumentBuilder();
		document = builder.parse("Users//Users.xml");
	}
		
	public void write( String login , String password , String group ) throws TransformerFactoryConfigurationError, FileNotFoundException, TransformerException{
		Element node = document.createElement("user");
		node.setAttribute("login",login);
		node.setAttribute("password",password);
		node.setAttribute("group",group);
		Element root = document.getDocumentElement();
		root.appendChild(node);
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer();
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream("Users\\Users.xml")));
	}
}
